package com.koron.css2.clientCenter.impl;

import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.koron.common.bean.query.SeniorQueryBean;
import com.koron.css2.baseConfig.bean.MeterModelBean;
import com.koron.css2.baseConfig.bean.PrefStrategyBean;
import com.koron.css2.baseConfig.mapper.*;
import com.koron.css2.baseConfig.vo.MeterBoreVO;
import com.koron.css2.baseConfig.vo.MeterFactoryVO;
import com.koron.css2.baseConfig.vo.SelectVO;
import com.koron.css2.baseConfig.vo.WaterTypeVO;
import com.koron.css2.clientCenter.Enum.UserInfoExportEnum;
import com.koron.css2.clientCenter.bean.AccountInfoBean;
import com.koron.css2.clientCenter.bean.ReadCycleConfigBean;
import com.koron.css2.clientCenter.mapper.AccountInfoMapper;
import com.koron.css2.clientCenter.mapper.UserInfoMapper;
import com.koron.css2.clientCenter.queryBean.UserInfoQueryBean;
import com.koron.css2.common.dto.AttachmentDto;
import com.koron.css2.common.service.AbstractExportBigExcel;
import com.koron.css2.serviceManage.bean.DistrictBean;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.SelectBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.DistrictMapper;
import com.koron.css2.serviceManage.mapper.PubAdminAreaMapper;
import com.koron.css2.serviceManage.utils.CommonUtils;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

public class UserInfoExport extends AbstractExportBigExcel {

	@Override
	public AttachmentDto getAttachment(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		AttachmentDto attachment = new AttachmentDto();
		attachment.setFileTemplate("AccountBalanceReportExport.xlsx");
		attachment.setFilename("用户资料" + CommonUtils.getCurrentDate());
		attachment.setExpType(AttachmentDto.ExpType.WRITE_TYPE);
		return attachment;
	}

	@Override
	public long count(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		UserInfoQueryBean uiqBean = JsonUtils.objectToPojo(req.getData(), UserInfoQueryBean.class);
		//判断综合查询list是否存在
		if (uiqBean.getList() != null && uiqBean.getList().size() > 0) {
			Iterator<SeniorQueryBean> it = uiqBean.getList().iterator();
			while (it.hasNext()) {
				SeniorQueryBean itBean = it.next();
				if (itBean.getFieldName().equals("stopMonths")) {
					Integer stopMonths = Integer.valueOf(itBean.getQueryValue());
					String stopMonthStr = LocalDate.now().minusMonths(stopMonths).toString();
					uiqBean.setStopMonthStr(stopMonthStr);
					it.remove();
				}
			}
		}
		if (uiqBean.getList() != null && uiqBean.getList().size() > 0) {
			uiqBean.setList(concatSql(uiqBean.getList()));
		}
		if (uiqBean.getUseWaterType() != null && uiqBean.getUseWaterType().length > 0) {
			uiqBean.setWaterTypeId(uiqBean.getUseWaterType()[uiqBean.getUseWaterType().length - 1]);
			uiqBean.setWaterTypeLev(uiqBean.getUseWaterType().length);
		}
		UserInfoMapper uiMapper = factory.getMapper(UserInfoMapper.class);
		//当模糊查询的条件为银行编号时单独处理
		if (uiqBean.getQueryType() == 6 && !StringUtils.isBlank(uiqBean.getFuzzyQuery())) {
			//先去accountInfo表查找
			AccountInfoMapper accountInfoMapper = factory.getMapper(AccountInfoMapper.class);
			AccountInfoBean bean = accountInfoMapper.getAccountByBankNo(uiqBean.getFuzzyQuery());
			//再去调用用户接口
			uiqBean.setQueryType(3);
			uiqBean.setFuzzyQuery(bean==null?null:bean.getAccountNo());
		}
		//当模糊查询的条件为优惠策略时单独处理
		if (uiqBean.getQueryType() == 9 && !StringUtils.isBlank(uiqBean.getFuzzyQuery())) {
			PrefStrategyMapper mapper = factory.getMapper(PrefStrategyMapper.class);
			List<PrefStrategyBean> bean = mapper.selectPrefStrategysByname(uiqBean.getFuzzyQuery());
			if (bean != null && bean.size() > 0) {
				uiqBean.setPrefStrategyBeans(bean);
			}
		}
		//营业区域单独处理
		if (uiqBean.getBusinessArea() != null && !"".equals(uiqBean.getBusinessArea())) {
			BusinessAreaMapper mapper = factory.getMapper(BusinessAreaMapper.class);
			List<String> areaIdList = queryChildrenArea(uiqBean.getBusinessArea(), userInfo.getCurWaterCode(), mapper);
			uiqBean.setBusinessAreaList(areaIdList);
		}
		return uiMapper.countUserInfoExport(uiqBean);
	}

	@Override
	public List getData(SessionFactory factory, UserInfoBean userInfo, RequestBean req, int page, int pageSize) {
		UserInfoQueryBean uiqBean = JsonUtils.objectToPojo(req.getData(), UserInfoQueryBean.class);
		//判断综合查询list是否存在
		if(uiqBean.getList() != null  && uiqBean.getList().size() > 0) {
			uiqBean.setList(concatSql(uiqBean.getList()));
		}
		//通过前端参数获取枚举中的字段名和查询字段名
		List<String> titles = new ArrayList<>();
		List<String> exportList = uiqBean.getExportList();
		String queryField = "";
		for (String name : exportList) {
			queryField += UserInfoExportEnum.fieldName(name) + ",";
			titles.add(UserInfoExportEnum.excelName(name));
		}
		//去掉最后一个逗号
		queryField = queryField.substring(0, queryField.length() - 1);
		uiqBean.setQueryField(queryField);
		int titleCount = 0;
		Map<String, String> title = new LinkedHashMap<>();
		for (String item : titles){
			title.put("key" + ++titleCount, item);
		}
		//设置用水类型
		if (uiqBean.getUseWaterType() != null && uiqBean.getUseWaterType().length > 0) {
			uiqBean.setWaterTypeId(uiqBean.getUseWaterType()[uiqBean.getUseWaterType().length-1]);
			uiqBean.setWaterTypeLev(uiqBean.getUseWaterType().length);
		}
		//营业区域单独处理
		if (uiqBean.getBusinessArea() != null && !"".equals(uiqBean.getBusinessArea())) {
			BusinessAreaMapper mapper = factory.getMapper(BusinessAreaMapper.class);
			List<String> areaIdList = queryChildrenArea(uiqBean.getBusinessArea(), userInfo.getCurWaterCode(), mapper);
			uiqBean.setBusinessAreaList(areaIdList);
		}
		List<Map<String, String>> result = getSQLResult(factory, page, pageSize, uiqBean, userInfo);
		Collection<String> values = title.values();
		List<List<String>> rowData = new ArrayList<List<String>>();
		rowData.add(Lists.newArrayList(values));
		for(Map<String, String> map : result) {
			rowData.add(Lists.newArrayList(map.values()));
		}
		return rowData;
	}

	/**
	 * 拼接综合查询条件sql
	 * @param list
	 * @return
	 */
	private List<SeniorQueryBean> concatSql(List<SeniorQueryBean> list){
		List<SeniorQueryBean> first = new ArrayList();
		Map<String,List<SeniorQueryBean>> map=list.stream().collect(Collectors.groupingBy(SeniorQueryBean::getFieldName));
		for (Map.Entry<String, List<SeniorQueryBean>> entry : map.entrySet()) {
			//排序，将与逻辑放在最前面
			List<SeniorQueryBean> mapList = entry.getValue().stream().sorted(Comparator.comparing(SeniorQueryBean::getLogicalValue)).collect(Collectors.toList());
			//拼接sql
			for (SeniorQueryBean seniorQueryBean : mapList) {
				if("bh".equals(seniorQueryBean.getOperator())) {
					seniorQueryBean.setOperator("like");
					seniorQueryBean.setQueryValue(" concat('%'," + "'" + seniorQueryBean.getQueryValue() + "'" + ",'%')");
				}else {
					seniorQueryBean.setQueryValue("'"+seniorQueryBean.getQueryValue()+"'");
				}
			}
			mapList.get(0).setFieldName("(" + mapList.get(0).getFieldName());
			mapList.get(mapList.size() - 1).setQueryValue(mapList.get(mapList.size() - 1).getQueryValue()+")");
			for (SeniorQueryBean seniorQueryBean : mapList) {
				first.add(seniorQueryBean);
			}
		}
		return first;
	}

	private static List<String> queryChildrenArea(String parentId, String groupCode, BusinessAreaMapper mapper) {
		List<SelectBean> list = mapper.findBusinessAreaByParentId(parentId, groupCode);
		List<String> result = new ArrayList<>();
		if (list != null && list.size() > 0) {
			result.addAll(list.stream().map(SelectBean::getId).collect(Collectors.toList()));
		} else {
			result = null;
		}
		return result;
	}

	private List<Map<String, String>> getSQLResult(SessionFactory factory, int start, int end, UserInfoQueryBean uiqBean, UserInfoBean userInfo){
		UserInfoMapper uiMapper = factory.getMapper(UserInfoMapper.class);
		PubAdminAreaMapper pmapper = factory.getMapper(PubAdminAreaMapper.class, "_default");
		PageHelper.startPage(start, end, false);
		List<LinkedHashMap<String, String>> uiList = uiMapper.userInfoExport(uiqBean);
		// 获取营业所名称
		List<SelectVO> businessAbodeList = factory.getMapper(BusinessAbodeMapper.class).businessAbodeSelect(userInfo.getCurWaterCode());
		//营业区域
		List<SelectVO> businessAreaList = factory.getMapper(BusinessAreaMapper.class).select(null, userInfo.getCurWaterCode());
		//行业分类
		List<SelectVO> tradeClassifyList = factory.getMapper(TradeClassifyMapper.class).tradeClassifySelect();
		//用水类型
		List<WaterTypeVO> waterTypeList = factory.getMapper(WaterTypeMapper.class).findWaterType(null);
		//开户银行(购买方开户银行)
		List<SelectVO> openAccountBankList = factory.getMapper(BankMapper.class).bankSelect();
//		//购买方开户银行
//		List<SelectVO> invoiceBankList = factory.getMapper(BankMapper.class).bankSelect();
		//水表厂家
		List<MeterFactoryVO> meterFactoryList = factory.getMapper(MeterFactoryMapper.class).selectMeterFactoryList(null);
		//水表口径
		List<MeterBoreVO> meterBoreList = factory.getMapper(MeterBoreMapper.class).selectMeterBoreList(null);

		//抄表周期
		List<ReadCycleConfigBean>  readCycleList=factory.getMapper(UserInfoMapper.class).readCycleConfigList();

		List<Map<String, String>> fList = new ArrayList<Map<String, String>>();
		for (Map<String, String> uiMap : uiList) {
			//抄表周期
			if(uiMap.containsKey("meter_reading_cycle") && StringUtils.isNotBlank(uiMap.get("meter_reading_cycle").toString())){
				for (ReadCycleConfigBean readCycle : readCycleList) {
					if (readCycle.getId().equals(uiMap.get("meter_reading_cycle"))) {
						uiMap.put("meter_reading_cycle", readCycle.getName());
						break;
					}
				}
			}

			//客户类型数据字典
			if (uiMap.containsKey("ctm_type") && StringUtils.isNotBlank(uiMap.get("ctm_type").toString())) {
				uiMap.put("ctm_type", Tools.getDicNameByCodeAndValue(factory, "CTT", uiMap.get("ctm_type").toString()));
			}
			//证件类型数据字典
			if (uiMap.containsKey("cert_type") && StringUtils.isNotBlank(uiMap.get("cert_type").toString())){
				uiMap.put("cert_type", Tools.getDicNameByCodeAndValue(factory, "IDT", uiMap.get("cert_type").toString()));
			}
			//信用等级数据字典
			if (uiMap.containsKey("credit_level") && StringUtils.isNotBlank(uiMap.get("credit_level").toString())){
				uiMap.put("credit_level", Tools.getDicNameByCodeAndValue(factory, "CDL", uiMap.get("credit_level").toString()));
			}
			//账户类型数据字典
			if (uiMap.containsKey("account_type") && StringUtils.isNotBlank(uiMap.get("account_type").toString())){
				uiMap.put("account_type", Tools.getDicNameByCodeAndValue(factory, "ACT", uiMap.get("account_type").toString()));
			}
			//缴费方式数据字典
			if (uiMap.containsKey("pay_way") && StringUtils.isNotBlank(uiMap.get("pay_way").toString())){
				uiMap.put("pay_way", Tools.getDicNameByCodeAndValue(factory, "BPW", uiMap.get("pay_way").toString()));
			}
			//用户状态数据字典
			if (uiMap.containsKey("status") && StringUtils.isNotBlank(uiMap.get("status").toString())){
				uiMap.put("status", Tools.getDicNameByCodeAndValue(factory, "CUS", uiMap.get("status").toString()));
			}
			//投递方式数据字典
			if (uiMap.containsKey("deliver_way") && StringUtils.isNotBlank(uiMap.get("deliver_way").toString())){
				uiMap.put("deliver_way", Tools.getDicNameByCodeAndValue(factory, "SDW", uiMap.get("deliver_way").toString()));
			}
			//发票类型数据字典
			if (uiMap.containsKey("invoice_type") && StringUtils.isNotBlank(uiMap.get("invoice_type").toString())){
				uiMap.put("invoice_type", Tools.getDicNameByCodeAndValue(factory, "BBT", uiMap.get("invoice_type").toString()));
			}
			//水表分类数据字典
			if (uiMap.containsKey("meter_type") && StringUtils.isNotBlank(uiMap.get("meter_type").toString())){
				uiMap.put("meter_type", Tools.getDicNameByCodeAndValue(factory, "MMT", uiMap.get("meter_type").toString()));
			}
			//水表传感器数据字典
			if (uiMap.containsKey("meter_sensor") && StringUtils.isNotBlank(uiMap.get("meter_sensor").toString())){
				uiMap.put("meter_sensor", Tools.getDicNameByCodeAndValue(factory, "MSS", uiMap.get("meter_sensor").toString()));
			}
			//传输方式数据字典
			if (uiMap.containsKey("transmittal_model") && StringUtils.isNotBlank(uiMap.get("transmittal_model").toString())){
				uiMap.put("transmittal_model", Tools.getDicNameByCodeAndValue(factory, "TPW", uiMap.get("transmittal_model").toString()));
			}

			//水表用途数据字典
			if (uiMap.containsKey("meter_use") && StringUtils.isNotBlank(uiMap.get("meter_use").toString())){
				uiMap.put("meter_use", Tools.getDicNameByCodeAndValue(factory, "CMC", uiMap.get("meter_use").toString()));
			}
			//用水对象数据字典
			if (uiMap.containsKey("use_water_object") && StringUtils.isNotBlank(uiMap.get("use_water_object").toString())){
				uiMap.put("use_water_object", Tools.getDicNameByCodeAndValue(factory, "UWS", uiMap.get("use_water_object").toString()));
			}
			//拆表类型数据字典
			if (uiMap.containsKey("split_meter_way") && StringUtils.isNotBlank(uiMap.get("split_meter_way").toString())){
				uiMap.put("split_meter_way", Tools.getDicNameByCodeAndValue(factory, "MRM", uiMap.get("split_meter_way").toString()));
			}
			//装表位置数据字典
			if (uiMap.containsKey("setup_meter_location") && StringUtils.isNotBlank(uiMap.get("setup_meter_location").toString())){
				uiMap.put("setup_meter_location", Tools.getDicNameByCodeAndValue(factory, "CTL", uiMap.get("setup_meter_location").toString()));
			}
			//行政区域
			if (uiMap.containsKey("admin_area") && StringUtils.isNotBlank(uiMap.get("admin_area").toString())){
				DistrictBean district = factory.getMapper(DistrictMapper.class).findDistrictById(uiMap.get("admin_area").toString());
				uiMap.put("admin_area", district==null?"":district.getSname());
			}
			if (uiMap.containsKey("business_abode") && StringUtils.isNotBlank(uiMap.get("business_abode").toString())){// 获取营业所名称
				for (SelectVO businessAbode : businessAbodeList) {
					if (businessAbode.getId().equals(uiMap.get("business_abode"))) {
						uiMap.put("business_abode", businessAbode.getName());
						break;
					}
				}
			}
			if (uiMap.containsKey("business_area") && StringUtils.isNotBlank(uiMap.get("business_area").toString())){//营业区域
				for (SelectVO businessArea : businessAreaList) {
					if (businessArea.getId().equals(uiMap.get("business_area"))) {
						uiMap.put("business_area", businessArea.getName());
						break;
					}
				}
			}
			if (uiMap.containsKey("trade_classify") && StringUtils.isNotBlank(uiMap.get("trade_classify").toString())){//行业分类
				for (SelectVO tradeClassify : tradeClassifyList) {
					if (tradeClassify.getId().equals(uiMap.get("trade_classify"))) {
						uiMap.put("trade_classify", tradeClassify.getName());
						break;
					}
				}
			}
			if (uiMap.containsKey("use_water_type") && StringUtils.isNotBlank(uiMap.get("use_water_type").toString())){//用水类型
				for (WaterTypeVO waterType : waterTypeList) {
					if (waterType.getId().equals(uiMap.get("use_water_type"))) {
						uiMap.put("use_water_type", waterType.getWaterTypeName());
						break;
					}
				}
			}
			if (uiMap.containsKey("open_account_bank") && StringUtils.isNotBlank(uiMap.get("open_account_bank").toString())){//开户银行
				for (SelectVO openBank : openAccountBankList) {
					if (openBank.getId().equals(uiMap.get("open_account_bank"))) {
						uiMap.put("open_account_bank", openBank.getName());
						break;
					}
				}
			}
			if (uiMap.containsKey("invoice_bank") && StringUtils.isNotBlank(uiMap.get("invoice_bank").toString())){//购买方开户银行
				for (SelectVO openBank : openAccountBankList) {
					if (openBank.getId().equals(uiMap.get("invoice_bank"))) {
						uiMap.put("invoice_bank", openBank.getName());
						break;
					}
				}
			}
			if (uiMap.containsKey("meter_factory") && StringUtils.isNotBlank(uiMap.get("meter_factory").toString())){//水表厂家
				for (MeterFactoryVO meterFactory : meterFactoryList) {
					if (meterFactory.getId().equals(uiMap.get("meter_factory"))) {
						uiMap.put("meter_factory", meterFactory.getFactoryName());
						break;
					}
				}
			}
			if (uiMap.containsKey("meter_model") && StringUtils.isNotBlank(uiMap.get("meter_model").toString())){//水表型号
				MeterModelMapper modelMapper = factory.getMapper(MeterModelMapper.class);
				MeterModelBean meterBean = modelMapper.selectMeterModelById(uiMap.get("meter_model").toString());
				if(null != meterBean) {
					uiMap.put("meter_model", meterBean.getModelName());
				}
			}

			if (uiMap.containsKey("meter_bore") && StringUtils.isNotBlank(uiMap.get("meter_bore").toString())){//水表口径
				for (MeterBoreVO meterBore : meterBoreList) {
					if (meterBore.getId().equals(uiMap.get("meter_bore"))) {
						uiMap.put("meter_bore", meterBore.getBoreName());
						break;
					}
				}
			}
			if(uiMap.containsKey("client_addr") && StringUtils.isNotBlank(uiMap.get("client_addr").toString())) {
				String area = pmapper.selectFullNameById(uiMap.get("client_addr").toString());
				uiMap.put("client_addr",area);
			}
			if(uiMap.containsKey("client_contract_addr") && StringUtils.isNotBlank(uiMap.get("client_contract_addr").toString())) {
				String area = pmapper.selectFullNameById(uiMap.get("client_contract_addr").toString());
				uiMap.put("client_contract_addr",area);
			}
			//遍历map，将key改为key1，key2。。。
			Map<String, String> lmap = new LinkedHashMap();
			List<String> fieldList = new ArrayList<String>();
			int mapCount = 1;
			//按顺序存放值
			for (Map.Entry<String, String> entry : uiMap.entrySet()) {
				fieldList.add(entry.getValue());
			}
			for (String object : fieldList) {
				lmap.put("key" + mapCount++, object);
			}
			fList.add(lmap);
		}
		return fList;
	}
}

